package com.example.myapplication.ui.cinema

import com.example.myapplication.ui.movie.Cinema_ChooseTimeSlot

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.android_program.data_class.cinemalist_2
import com.example.android_program.data_class.movie_1_1
import com.example.myapplication.R
import com.example.myapplication.ui.home.HomeFragment
import kotlinx.android.synthetic.main.fragment_cinema.*
import kotlinx.android.synthetic.main.fragment_home.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.lang.Exception
import java.lang.StringBuilder
import java.lang.reflect.Field
import kotlin.concurrent.thread

class CinemaFragment : Fragment() {
    val cinemalist: ArrayList<cinemalist_2> = ArrayList()
    private lateinit var cinemaViewModel: CinemaViewModel
    val sever_ip = "192.168.43.8"
    val showAll_Cinema_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_Cinema.jsp"
    //val showAll_Cinema_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/showAll_Cinema.jsp"
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        cinemaViewModel =
                ViewModelProviders.of(this).get(CinemaViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_cinema, container, false)

     return root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        Recycler_data_2()  //列表数据
        Recycler_2_initView() //列表初始化


    }

    //------------------------------------------------------------------------------------------------------------------
    private fun Recycler_2_initView() {
        val layoutManager = LinearLayoutManager(context)
        myrecyclerview2.layoutManager = layoutManager
        val adapter2 = CinemalistAapter(cinemalist, this.requireContext())
        myrecyclerview2.adapter = adapter2
    }

    fun Recycler_data_2() {
        /*cinemalist.add(
            cinemalist_2(
                "星空国际影院(临安店)",
                "临安区临安市临安区春天华府生活广场3楼",
                "19.1",
                "1.6",
                R.drawable.p_cinema_1,
                R.drawable.p_cinema_2,
                R.drawable.p_cinema_3,
                R.drawable.p_cinema_4,
                R.drawable.p_cinema_5
            )
        )
        cinemalist.add(
            cinemalist_2(
                "大地影院(临安店)",
                "临安区临安市锦城临安宝龙广场",
                "29.1",
                "1.0",
                R.drawable.p_cinema_1,
                R.drawable.p_cinema_2,
                R.drawable.p_cinema_3,
                R.drawable.p_cinema_4,
                R.drawable.p_cinema_w
            )
        )
        cinemalist.add(
            cinemalist_2(
                "星空国际影院(临安店)",
                "临安区临安市临安区春天华府生活广场3楼",
                "19.1",
                "1.6",
                R.drawable.p_cinema_1,
                R.drawable.p_cinema_2,
                R.drawable.p_cinema_3,
                R.drawable.p_cinema_4,
                R.drawable.p_cinema_5
            )
        )
        cinemalist.add(
            cinemalist_2(
                "大地影院(临安店)",
                "临安区临安市锦城临安宝龙广场",
                "29.1",
                "1.0",
                R.drawable.p_cinema_1,
                R.drawable.p_cinema_2,
                R.drawable.p_cinema_3,
                R.drawable.p_cinema_4,
                R.drawable.p_cinema_w
            )
        )
        cinemalist.add(
            cinemalist_2(
                "星空国际影院(临安店)",
                "临安区临安市临安区春天华府生活广场3楼",
                "19.1",
                "1.6",
                R.drawable.p_cinema_1,
                R.drawable.p_cinema_2,
                R.drawable.p_cinema_3,
                R.drawable.p_cinema_4,
                R.drawable.p_cinema_5
            )
        )
        cinemalist.add(
            cinemalist_2(
                "大地影院(临安店)",
                "临安区临安市锦城临安宝龙广场",
                "29.1",
                "1.0",
                R.drawable.p_cinema_1,
                R.drawable.p_cinema_2,
                R.drawable.p_cinema_3,
                R.drawable.p_cinema_4,
                R.drawable.p_cinema_w
            )
        )*/
        getAllTrainInfoJson()
    }
    private class CinemalistViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var cinemalist_all: LinearLayout = view.findViewById(R.id.cinemelist_all)
        var cinemalist_2_name_1: TextView = view.findViewById(R.id.cinemalist_name)
        var cinemalist_2_location_1: TextView = view.findViewById(R.id.cinemalist_location)
        var cinemalist_2_price_1: TextView = view.findViewById(R.id.cinemalist_price)
        var cinemalist_2_distance_1: TextView = view.findViewById(R.id.cinemalist_distance)
        var cinemalist_2_img1_1: ImageView = view.findViewById(R.id.cinemapng_1)
        var cinemalist_2_img2_1: ImageView = view.findViewById(R.id.cinemapng_2)
        var cinemalist_2_img3_1: ImageView = view.findViewById(R.id.cinemapng_3)
        var cinemalist_2_img4_1: ImageView = view.findViewById(R.id.cinemapng_hdimg_1)
        var cinemalist_2_img5_1: ImageView = view.findViewById(R.id.cinemapng_hdimg_2)
    }
    //适配器
    private class CinemalistAapter(val cinemalist: List<cinemalist_2>, val context: Context):
        RecyclerView.Adapter<CinemalistViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CinemalistViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_cinemalist, parent, false)
            //点击事件  获取点击的  list 中的数据
            val viewHolder = CinemalistViewHolder(view)
            viewHolder.cinemalist_all.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = cinemalist[position]
                Toast.makeText(parent.context,"${info.cinemalist_2_name}", Toast.LENGTH_LONG).show()
                val mIntent = Intent(context, Cinema_ChooseTimeSlot::class.java)
                mIntent.putExtra("cinema_name", cinemalist[position].cinemalist_2_name)//可能要改进
                mIntent.putExtra("cinema_address", cinemalist[position].cinemalist_2_location)//可能要改进
                mIntent.putExtra("movie_name", "疯狂原始人")//默认把疯狂原始人传过去
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                context.startActivity(mIntent)
            }
            return viewHolder
        }
        override fun onBindViewHolder(holder: CinemalistViewHolder, position: Int) {
            val info = cinemalist[position]
            holder.cinemalist_2_name_1.text = info.cinemalist_2_name
            holder.cinemalist_2_location_1.text = info.cinemalist_2_location
            holder.cinemalist_2_price_1.text = info.cinemalist_2_price
            holder.cinemalist_2_distance_1.text = info.cinemalist_2_distance
            holder.cinemalist_2_img1_1.setImageResource(info.cinemalist_2_img_1)
            holder.cinemalist_2_img2_1.setImageResource(info.cinemalist_2_img_2)
            holder.cinemalist_2_img3_1.setImageResource(info.cinemalist_2_img_3)
            holder.cinemalist_2_img4_1.setImageResource(info.cinemalist_2_img_4)
            holder.cinemalist_2_img5_1.setImageResource(info.cinemalist_2_img_5)
        }
        override fun getItemCount(): Int {
            return cinemalist.size
        }
    }
//---------------------------------------------------------------------------------------------

    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                //构建请求
                val request = Request.Builder()
                    .url(showAll_Cinema_jsp)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
                //txtData.text = responseData
                val result = parseJson(responseData)
                if (responseData != null){
                    activity?.runOnUiThread{
                        //修改布局
                        //txtData.text = result
                        val layoutManager = LinearLayoutManager(context)
                        myrecyclerview2.layoutManager = layoutManager
                        val adapter2 = CinemalistAapter(cinemalist, this.requireContext())
                        myrecyclerview2.adapter = adapter2

                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson(jsonData:String?):String{
        val builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            cinemalist.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val cinema_name = jsonObject.getString("cinema_name")
                val cinema_location = jsonObject.getString("cinema_location")
                val cinema_price = jsonObject.getString("cinema_price")
                val cinema_distance = jsonObject.getString("cinema_distance")
                val cinema_img_1 = jsonObject.getString("cinema_img_1")
                val cinema_img_2 = jsonObject.getString("cinema_img_2")
                val cinema_img_3 = jsonObject.getString("cinema_img_3")
                val cinema_img_4 = jsonObject.getString("cinema_img_4")
                val cinema_img_5 = jsonObject.getString("cinema_img_5")

                //builder.append("$movie_name--$movie_src--$movie_score--$movie_kind, ")
                cinemalist.add(
                    cinemalist_2(cinema_name, cinema_location, cinema_price,cinema_distance,
                        getResourceIdByString(cinema_img_1), getResourceIdByString(cinema_img_2),
                        getResourceIdByString(cinema_img_3), getResourceIdByString(cinema_img_4),
                        getResourceIdByString(cinema_img_5))
                )


            }
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getResourceIdByString(s: String?): Int {
        try {
            val field: Field = R.drawable::class.java.getField(s)
            return field[null].toString().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }
}